package com.document.dao;

import java.util.ArrayList;
import java.util.List;

import org.nutz.dao.Cnd;

import com.document.model.Org;

public class OrgDao extends BasicDao {
	
	/**
	 * 最小子组织CODE
	 */
	private final int MIN_ORGCODE = 0;
	
	/**
	 * 查询当前组织下的最大子组织的编码
	 * @param orgId
	 * @return
	 */
	public int findMaxOrgCode(String orgCode){
		int maxCode = MIN_ORGCODE;
		Org org = null;
		if(orgCode == null || "".equals(orgCode)){
			org = findByCondition(Org.class, Cnd.wrap("INSTR(orgcode,'-')=0 order by Convert(orgcode,signed) desc"));
		}else{
			org = findByCondition(Org.class, Cnd.wrap("LENGTH(ORGCODE)>= " + (orgCode.length() + 2) 
					+ " and INSTR(SUBSTRING(orgcode," + (orgCode.length() + 2) 
					+"),'-')=0 order by Convert(substring(orgcode," + (orgCode.length() + 2) +"),signed) desc"));
		}
		if(org != null && org.getOrgCode() != null && !"".equals(org.getOrgCode())){
			maxCode = orgCode != null && !"".equals(orgCode) ? Integer.parseInt(org.getOrgCode().substring(orgCode.length() + 1))
					: Integer.parseInt(org.getOrgCode());
		}
		return maxCode;
	}
	
	/**
	 * 查找当前机构下的所有子机构
	 * @param orgCode
	 * @return
	 */
	public List<Org> findChildOrg(String orgCode){
		List<Org> orgList = null;
		if(orgCode != null && !"".equals(orgCode)){
			/*if("0".equals(orgCode)){
				orgList = search(Org.class, Cnd.wrap("INSTR(orgcode,'-')=0 "));
			}else {*/
				orgList = search(Org.class, Cnd.wrap("INSTR(SUBSTRING(orgcode," + (orgCode.length() + 2) 
						+"),'-')=0 AND orgcode like '" + orgCode + "-%'"));
//			}
		}
		if(orgList == null){
			orgList = new ArrayList<Org>();
		}
		return orgList;
	}
	
	public boolean batchDeleteOrg(String[] orgCodes){
		try{
			for(String orgCode : orgCodes){
				delete("b_org", Cnd.where("orgcode", "like", orgCode + "-%").or("orgcode", "=", orgCode));
			}
		}catch(Exception e){
			return false;
		}
		return true;
	}
}
